package gredis

import (
	"context"

	"github.com/go-redis/redis"
)

// CACHE总管理器
type CACHEManager struct {
	GroupMap map[string]*CACHEGroup
}

func NewRedis(config *CACHEConf) (cacheMgr *CACHEManager, err error) {
	cacheMgr = &CACHEManager{
		GroupMap: make(map[string]*CACHEGroup),
	}

	if config == nil || config.GroupConfList == nil {
		return
	}

	// 按Name索引每一个CACHEGroup
	groupConfList := config.GroupConfList
	for i := 0; i < len(groupConfList); i++ {
		var cacheGroup *CACHEGroup
		if cacheGroup, err = newCACHEGroup(&groupConfList[i]); err != nil {
			return
		}
		cacheMgr.GroupMap[groupConfList[i].Name] = cacheGroup
	}

	GERedis = cacheMgr
	return
}

// 获取redis主从实例
func (cacheMgr *CACHEManager) Instance(ctx context.Context, name string, optionFuncs ...OptionFunc) (cacheClient *CacheClient, err error) {
	cacheGroup, existed := cacheMgr.GroupMap[name]
	if !existed {
		err = ERR_CACHE_GROUP_NOT_FOUND
		return
	}
	cacheClient = newCacheClient(ctx, cacheGroup, optionFuncs...)
	return
}

// 获取redis集群实例
func (cacheMgr *CACHEManager) InstanceCluster(ctx context.Context, name string) (client *redis.ClusterClient, err error) {
	cacheGroup, existed := cacheMgr.GroupMap[name]
	if !existed {
		err = ERR_CACHE_GROUP_NOT_FOUND
		return
	}
	client, err = cacheGroup.ChooseClusterConn(ctx)
	return
}
